package com.javatest.validate;

import javax.validation.ConstraintViolation;
import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.lang.reflect.Method;
import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @date 2020-11-10 上午9:31
 */
public class PersonService {
    @NotNull
    public Person getOne(@NotNull @Min(1) Integer id, String name) throws NoSuchMethodException {
        // ... 模拟逻辑执行，得到一个result
        Person result = null;

        // 在结果返回之前校验
        Method currMethod = this.getClass().getMethod("getOne", Integer.class, String.class);
        Set<ConstraintViolation<PersonService>> validResult = ValidationUtils
                .obtainExecutableValidator()
                .validateReturnValue(this, currMethod, result);
        if (!validResult.isEmpty()) {
            // ... 输出错误详情validResult
            validResult.stream().map(v -> v.getPropertyPath() + " "
                    + v.getMessage() + ": "
                    + v.getInvalidValue())
                    .forEach(System.out::println);
            throw new IllegalArgumentException("参数错误");
        }
        return result;
    }

    public void save(@NotNull @Valid Person person) throws NoSuchMethodException {
        Method currMethod = this.getClass().getMethod("save", Person.class);
        Set<ConstraintViolation<PersonService>> validResult = ValidationUtils.obtainExecutableValidator()
                .validateParameters(this, currMethod, new Object[]{person});
        if (!validResult.isEmpty()) {
            // ... 输出错误详情validResult
            validResult.stream().map(v -> v.getPropertyPath() + " "
                    + v.getMessage() + ": "
                    + v.getInvalidValue())
                    .forEach(System.out::println);
            throw new IllegalArgumentException("参数错误");
        }
    }
}
